package com.bruce.asurada.sso.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.InetSocketAddress;
import java.net.Socket;

/**
 * Nacos 配置类
 * 用于调试和监控 Nacos 连接状态
 */
@Slf4j
@Configuration
public class NacosConfig {

    @Value("${spring.cloud.nacos.server-addr:}")
    private String serverAddr;

    @Value("${spring.cloud.nacos.discovery.namespace:}")
    private String namespace;

    @Value("${spring.application.name}")
    private String applicationName;

    @Bean
    public ApplicationRunner nacosConnectionChecker() {
        return args -> {
            log.info("=== Nacos 配置信息 ===");
            log.info("服务器地址: {}", serverAddr);
            log.info("命名空间: {}", namespace);
            log.info("应用名称: {}", applicationName);
            log.info("==================");
            
            // 检查网络连接
            try {
                String[] hostPort = serverAddr.split(":");
                String host = hostPort[0];
                int port = Integer.parseInt(hostPort[1]);
                
                log.info("正在检查 Nacos 服务器连接: {}:{}", host, port);
                
                try (Socket socket = new Socket()) {
                    socket.connect(new InetSocketAddress(host, port), 5000);
                    log.info("✅ Nacos 服务器连接成功");
                } catch (Exception e) {
                    log.error("❌ Nacos 服务器连接失败: {}", e.getMessage());
                    log.error("请检查:");
                    log.error("1. Nacos 服务器是否启动");
                    log.error("2. 网络连接是否正常");
                    log.error("3. 防火墙设置");
                }
            } catch (Exception e) {
                log.error("解析服务器地址失败: {}", e.getMessage());
            }
        };
    }
}